package com.wingsfrog.ZcVideo;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.Player.Source.TAlarmSetInfor;
import com.Player.Source.TDevNodeInfor;
import com.wingsfrog.ZcVideo.PlayLayout.ShowStopLayoutListener;
import com.wingsfrog.genius_rc.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FgPlay extends Fragment implements OnClickListener {
	final String TAG = "FgPlay--->";
	// 云台控制命令
	public static final byte MD_STOP = 0; // 停止
	public static final byte MD_LEFT = 11; // 左
	public static final byte MD_RIGHT = 12; // 右
	public static final byte MD_UP = 9; // 上
	public static final byte MD_DOWN = 10; // 下
	public static final byte CORE_UP_LEFT = 35; // 左上
	public static final byte CORE_UP_RIGHT = 36; // 右上
	public static final byte CORE_DOWN_LEFT = 37; // 左下
	public static final byte CORE_DOWN_RIGHT = 38; // 右下
	public static final byte ACTION_ZOOMADD = 6; // 拉近
	public static final byte ACTION_ZOOMReduce = 5;// 拉远
	public static final byte ACTION_FOCUSADD = 7;// 焦距+
	public static final byte ACTION_FOCUSReduce = 8;// 焦距减
	public static final byte ACTION_Circle_Add = 13; // 光圈+
	public static final byte ACTION_Circle_Reduce = 14;// 光圈-
	private static final String ROW_TOTAL = "ROW_TOTAL";
	public final static int requestCode = 4;

	private View view;
	private View layoutTitle, layoutMenu;
    private Button btnSound, btnStop, btnSnap;
	private ImageButton btnTalk, Talkbtn;
	private Button btnMenu, btnRotate;
	ImageButton btnAlarm;
	CheckBox btnRecord;
	public static boolean isLand = false;
	public PlayLayout playLayout;
	Activity context;
	private SharedPreferences sp;
	LayoutInflater inflater;
	ViewGroup container;
	private PlayNode playNode;
	private List<PlayNode> allChildNode;
	private ImageButton down, up, right, left;
//            leftDown, leftUp, rightUp, rightDown,
    private ImageButton btnFocusAdd, btnFocusSub;
	private RelativeLayout focusBg;
	private int length;
	private boolean isShowControlBtn = false;
	TextView tvState, tvState1, tvTitle;
//	public AppMain appMain;
	private Activity con;
	private boolean isShot = false;// 是否截图过
	public boolean isPlaying;

	TAlarmSetInfor alarmInfo;
	private String titleName;
	private int screenScale;
	public int currentStream = -1;
	public int currentChannel = 0;
	private ImageButton btnStream;
	private List<PlayNode> nodeList;
	public static int playerState = 0;

    private boolean isRotating = false; // 是否已经旋转

	public void setNodeList(List<PlayNode> nodeList) {
		if (this.nodeList == null) {
			this.nodeList = new ArrayList<PlayNode>();
		}
		this.nodeList.clear();
		this.nodeList.addAll(nodeList);
	}

	public void addNode(PlayNode node) {
		playNode = node;
		currentStream = -1;
//		getAlartState();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context = this.getActivity();
		titleName = "实时监控";
		context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		sp = context.getSharedPreferences(this.getClass().getName(),
				Context.MODE_PRIVATE);
//		screenScale = SharedPrefsUtil.getValue(context,
//				AcNativeSetting.SCREEN_SCALE, 0);

		// if (nodeList!=null) {
		// nodeList.clear();
		// }

		// Log.i("slide", "ActivityFragment-->onCreate");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i("slide", "ActivityFragment->onCreateView");
		this.inflater = inflater;
		this.container = container;
		con = this.getActivity();
//		appMain = (AppMain) con.getApplicationContext();
		if (view == null) {
			initeView(inflater, container);
		}
		if (isShowControlBtn) {
			showControlBtnEx(false);
		}

		playLayout.stopDelayed(false);
		playLayout.setScreenScale(screenScale == 1 ? true : false);
		initeListViewData();

		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}
		playLayout.startThread();

        showControlBtnEx(true);
		return view;

	}

	private void initeView(LayoutInflater inflater, ViewGroup container) {
		view = inflater.inflate(R.layout.fragment_play, container, false);
		tvTitle = (TextView) view.findViewById(R.id.tv_title);
		layoutTitle = view.findViewById(R.id.title_layout);
		btnMenu = (Button) view.findViewById(R.id.menu_btn);
		tvState = (TextView) view.findViewById(R.id.tvState);
		tvState1 = (TextView) view.findViewById(R.id.tvState1);
		btnMenu.setOnClickListener(this);

		layoutMenu = view.findViewById(R.id.menu_layout);
		btnSnap = (Button) view.findViewById(R.id.btn_snap);
		btnRecord = (CheckBox) view.findViewById(R.id.btn_record);
		btnAlarm = (ImageButton) view.findViewById(R.id.playview_cloud_alarm);
		btnStop = (Button) view.findViewById(R.id.playview_cloud_stop);

		btnSound = (Button) view.findViewById(R.id.playview_cloud_sound);
		btnTalk = (ImageButton) view.findViewById(R.id.playview_cloud_talk);
//		 OnCloudClick onCloudClick = new OnCloudClick();
		btnStream = (ImageButton) view.findViewById(R.id.playview_cloud_stream);
		btnStop.setOnClickListener(this);
		btnSound.setOnClickListener(this);
		btnTalk.setOnClickListener(this);
		btnSnap.setOnClickListener(this);
		btnAlarm.setOnClickListener(this);
		btnRecord.setOnClickListener(this);

        btnRotate = (Button) view.findViewById(R.id.playview_rotate);
        btnRotate.setOnClickListener(this);

		btnStream.setOnClickListener(this);




		// layoutControl.removeAllViews();
		// layoutControl.addView(layoutcloud1);

		initePlayLayout();
	}

	/**
	 * 给listView赋值
	 */
	public void initeListViewData() {
		/*if (TextUtils.isEmpty(Config.ThumbDir)) {
			if (appMain.getUserInfo() == null) {
				startActivity(new Intent(con, AcLogin.class));
				con.finish();
			}
		}*/
//		allChildNode = appMain.getAllChildNodeList();
        allChildNode = ZcVideo.GetAllChildren();
		if (playerState != 1) {
			if (allChildNode.size() <= 0 ) return;
			PlayNode node = allChildNode.get(allChildNode.size() - 1);
			if (node != null && node.isOnline()) {
				addNode(node);
				initePlayDataAndPlay();
			} else {
				// Show.toast(con, R.string.camera_offline);
			}
		}
		if (playNode != null) {
			boolean isExsit = false;
			for (int i = 0; i < allChildNode.size(); i++) {
				PlayNode node = allChildNode.get(i);
				if (playNode.getDeviceId().equals(node.getDeviceId())) {
					isExsit = true;
					playNode = node;
					break;
				}

			}
			if (!isExsit) {
				playLayout.release();
			}
			//getAlartState();
		}
		// if (allChildNode.size() == 1) {
		// allChildNode.add(new PlayNode());
		// }
		// if (allChildNode.size() == 1) {
		// }

		new GetThumb().execute();
	}

	/**
	 * 偏正gallery的第一个item靠左开始
	 * 
	 * @param gallery
	 */
	/*private void alignGalleryToLeft(Gallery gallery) {

		int galleryWidth = con.getWindowManager().getDefaultDisplay()
				.getWidth();
		int itemWidth = context.getResources().getDimensionPixelSize(
				R.dimen.gallery_item_width);
		int spacing = context.getResources().getDimensionPixelSize(
				R.dimen.gallery_spacing);
		int offset;
		if (galleryWidth <= itemWidth) {
			offset = galleryWidth / 2 - itemWidth / 2 - spacing;
		} else {
			offset = galleryWidth - itemWidth - 4 * spacing;
		}

		// Now update the layout parameters of the gallery in order to set the
		// left margin
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin,
				mlp.bottomMargin);
	}*/

	/*public void getAlartState() {
		if (playNode != null) {
			new GetAlarmSettingThread(playNode.getDeviceId(),
					appMain.getPlayerclient(), new Handler() {

						@Override
						public void handleMessage(Message msg) {
							alarmInfo = (TAlarmSetInfor) msg.obj;
							if (alarmInfo != null) {

								btnAlarm.setImageResource(Utils.showIfNotify(
										con, alarmInfo) ? R.drawable.playview_cloud_alarm_h
										: R.drawable.playview_cloud_alarm);

							}

						}

					}).start();
		}
	}*/

	class GetThumb extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			synchronized (FgPlay.this) {
				String thumDir = "/sdcard/NewUMEye/thumb/";
				File dir = new File(thumDir);
				File[] listFile = dir.listFiles();
				if (listFile == null) {
					return null;
				}
				if (allChildNode == null) {
					return null;
				}
				for (int i = 0; i < allChildNode.size(); i++) {
					// String id = allChildNode.get(i).getDeviceId();
					String id = allChildNode.get(i).getDeviceId() + ".jpg";
					Bitmap bitmap = null;
					for (int n = 0; n < listFile.length; n++) {
						/*
						 * if (id.equals(listFile[n].getName().split("-")[0])) {
						 * bitmap = Utility.GetThumbImage(listFile[n]
						 * .toString());
						 * 
						 * break; }
						 */
						if (id.equals(listFile[n].getName())) {
							bitmap = Utility.GetThumbImage(listFile[n]
									.toString());
							break;
						}
					}
					if (bitmap != null) {
						publishProgress();
					}
					// else {
					// Log.e("GetThumbImage error",
					// "GetThumbImage is null DeviceId is " + id);
					// }
				}

			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			Log.w("listFile", "listFile:");
			super.onProgressUpdate(values);
		}

	}

	int[] getListViewHight() {
		int[] listViewHight = new int[2];
		int[] location = new int[2];
		listViewHight[0] = location[1];
		return listViewHight;

	}

	public void initePlayDataAndPlay() {
		if (playNode != null) {
			playLayout.initeData(playNode, currentStream);

//			tvTitle.setText(playNode.getName());

			// nodeList.clear();
			// playLayout.playAll();
//			playLayout.play();
			isShot = false;
			playLayout.setIsAudio(false);
            btnSound.setBackgroundResource(R.drawable.playview_cloud_sound);
		}

	}

	/**
	 * 初始化播放
	 */
	public void initePlayLayout() {
		playLayout = (PlayLayout) view.findViewById(R.id.play_layout);
		playLayout.setTitleView(tvTitle);
		playLayout.setShowListener(new ShowStopLayout());
		playLayout.setStateChangeListener(new StateChange());
		playLayout.initeView(context, true);
		int row = sp.getInt(ROW_TOTAL, 4);

		playLayout.initeCanvas(row);
		configuration(getResources().getConfiguration());
	}

	/**
	 * 初始化8个方向的控制按钮
	 * 
	 * @param view
	 */
	void initeControlBtn(View view) {
		OnCloudClick onCloudClick = new OnCloudClick();
		down = (ImageButton) view.findViewById(R.id.btn_down);
		left = (ImageButton) view.findViewById(R.id.btn_left);
		up = (ImageButton) view.findViewById(R.id.btn_up);
		right = (ImageButton) view.findViewById(R.id.btn_right);
//		leftDown = (Button) view.findViewById(R.id.btn_left_down);
//		leftUp = (Button) view.findViewById(R.id.btn_left_up);
//		rightUp = (Button) view.findViewById(R.id.btn_right_up);
//		rightDown = (Button) view.findViewById(R.id.btn_right_down);

		focusBg = (RelativeLayout) view.findViewById(R.id.focusBg);
		btnFocusAdd = (ImageButton) view.findViewById(R.id.btn_foucos_add);
		btnFocusSub = (ImageButton) view.findViewById(R.id.btn_foucos_sub);

		Rect rect = new Rect(playLayout.getLeft(), playLayout.getTop(),
				playLayout.getRight(), playLayout.getBottom());
		// playLayout.getWindowVisibleDisplayFrame(rect);
		if (rect != null) {
//			int margin = rect.right - btnFocusAdd.getRight();
//			setAddPosition(btnFocusAdd, rect, margin);
//			setSubPosition(btnFocusSub, rect, margin);
		}

		btnFocusAdd.setOnTouchListener(onCloudClick);
		btnFocusSub.setOnTouchListener(onCloudClick);
		down.setOnTouchListener(onCloudClick);
		up.setOnTouchListener(onCloudClick);
		right.setOnTouchListener(onCloudClick);
		left.setOnTouchListener(onCloudClick);
//		leftDown.setOnTouchListener(onCloudClick);
//		leftUp.setOnTouchListener(onCloudClick);
//		rightUp.setOnTouchListener(onCloudClick);
//		rightDown.setOnTouchListener(onCloudClick);
	}

	void setAddPosition(Button btn, Rect rect, int margin) {
		FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) btn
				.getLayoutParams();

		int temp = (rect.bottom - 2 * margin - btn.getHeight()) / 4 + margin;
		Log.d("getDrawingRect", "getDrawingRect heiht:" + temp);
		params.setMargins(params.leftMargin, temp, params.rightMargin,
				params.bottomMargin);// 通过自定义坐标来放置你的控件
		btn.setLayoutParams(params);
	}

	void setSubPosition(Button btn, Rect rect, int margin) {
		FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) btn
				.getLayoutParams();

		int temp = (rect.bottom - 2 * margin - btn.getHeight()) / 4 + margin;
		Log.d("getDrawingRect", "getDrawingRect heiht:" + temp);
		params.setMargins(params.leftMargin, params.topMargin,
				params.rightMargin, temp);// 通过自定义坐标来放置你的控件
		btn.setLayoutParams(params);
	}

	/**
	 * 云台控制监听
	 * 
	 * @author Administrator
	 * 
	 */
	public class OnCloudClick implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int action = event.getAction();

			try {
				switch (v.getId()) {
				case R.id.btn_foucos_add:
					if (action == MotionEvent.ACTION_DOWN) {
						focusBg.setBackgroundResource(R.drawable.btn_focus_add);
					} else if (action == MotionEvent.ACTION_UP){
						focusBg.setBackgroundResource(R.drawable.btn_focus);
					}
					ExcuteCommand(btnFocusAdd, R.drawable.btn_add,
							R.drawable.btn_add_h, action, ACTION_FOCUSADD);
					break;
				case R.id.btn_foucos_sub:
					if (action == MotionEvent.ACTION_DOWN) {
						focusBg.setBackgroundResource(R.drawable.btn_focus_sub);
					} else if (action == MotionEvent.ACTION_UP){
						focusBg.setBackgroundResource(R.drawable.btn_focus);
					}
					ExcuteCommand(btnFocusSub, R.drawable.btn_sub,
							R.drawable.btn_sub_h, action,
							ACTION_FOCUSReduce);
					break;
				case R.id.btn_down:
					ExcuteCommand(down, R.drawable.btn_down_0,
							R.drawable.btn_down_1, action, MD_DOWN);
					break;
				case R.id.btn_left:
					ExcuteCommand(left, R.drawable.btn_left_0,
							R.drawable.btn_left_1, action, MD_LEFT);
					break;
				case R.id.btn_right:
					ExcuteCommand(right, R.drawable.btn_right_0,
							R.drawable.btn_right_1, action, MD_RIGHT);
					break;
				case R.id.btn_up:
					ExcuteCommand(up, R.drawable.btn_up_0, R.drawable.btn_up_1,
							action, MD_UP);
					break;
//				case R.id.btn_left_down:
//					ExcuteCommand(leftDown, R.drawable.btn_left_down_0,
//							R.drawable.btn_left_down_1, action, CORE_DOWN_LEFT);
//					break;
//				case R.id.btn_left_up:
//					ExcuteCommand(leftUp, R.drawable.btn_left_up_0,
//							R.drawable.btn_left_up_1, action, CORE_UP_LEFT);
//					break;
//				case R.id.btn_right_down:
//					ExcuteCommand(rightDown, R.drawable.btn_right_down_0,
//							R.drawable.btn_right_down_1, action,
//							CORE_DOWN_RIGHT);
//					break;
//				case R.id.btn_right_up:
//					ExcuteCommand(rightUp, R.drawable.btn_right_up_0,
//							R.drawable.btn_right_up_1, action, CORE_UP_RIGHT);
//					break;
				/*case R.id.talk:

					if (action == MotionEvent.ACTION_DOWN) {
						// playLayout.setPPT(false);
						Talkbtn.setImageResource(R.drawable.talk_h);
						playLayout.setPPT(true);

					} else if (action == MotionEvent.ACTION_UP) {
						Talkbtn.setImageResource(R.drawable.talk);
						playLayout.setPPT(false);

					}
					break;*/
				}
			} catch (Exception e) {

			}
			return true;
		}

	}

	/**
	 * 执行云台命令
	 * 
	 * @param action
	 *            按钮的上下
	 * @param command
	 *            云台命令
	 */
	private void ExcuteCommand(View btn, int bg0, int bg1, int action,
			byte command) {
		if (action == MotionEvent.ACTION_DOWN) {
			// isStopCloudCommand = false;

			if (btn instanceof ImageButton) {
				((ImageButton)btn).setImageResource(bg1);
			} else if (btn instanceof Button) {
				btn.setBackgroundResource(bg1);
			}

			if (command == MD_DOWN || command == MD_UP || command == MD_LEFT
					|| command == MD_RIGHT || command == CORE_UP_LEFT
					|| command == CORE_UP_RIGHT || command == CORE_DOWN_LEFT
					|| command == CORE_DOWN_RIGHT) {

				System.out.println("发送云台命令：" + command + ",云台步长：" + length);
				playLayout.setPTZ(command, length);
			} else {
				playLayout.setPTZ(command, 2);
				System.out.println("发送云台命令：" + command + ",云台步长：" + 0);
			}

		} else if (action == MotionEvent.ACTION_UP) {
			if (btn instanceof ImageButton) {
				((ImageButton)btn).setImageResource(bg0);
			} else if (btn instanceof Button) {
				btn.setBackgroundResource(bg0);
			}

			playLayout.setPTZ(MD_STOP, 0);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		configuration(newConfig);
		if (playLayout.isPPT()) {
			playLayout.setPPT(false);
//			Talkbtn.setImageResource(R.drawable.talk);
		}

	}

	public void configuration(Configuration newConfig) {

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

			isLand = true;
			layoutTitle.setVisibility(View.GONE);
			layoutMenu.setVisibility(View.GONE);
			// playLayout.setScreenScale(false);

			fullScreenChange(isLand);
			playLayout.setLand(isLand);

		} else {
			isLand = false;
			layoutTitle.setVisibility(View.VISIBLE);
			layoutMenu.setVisibility(View.VISIBLE);
			// playLayout.setScreenScale(screenScale == 0 ? true : false);
			fullScreenChange(isLand);
			playLayout.setLand(isLand);
		}

	}

	boolean showControlBtnEx(boolean show) {
		if (down == null) {
			initeControlBtn(view);
		}
		isShowControlBtn = show;
		return show;
	}

	/**
	 * 全屏隐藏通知栏
	 * 
	 * @param fullScreen
	 */
	public void fullScreenChange(boolean fullScreen) {

		Window window = context.getWindow();
		WindowManager.LayoutParams attrs = window.getAttributes();

		if (!fullScreen) {
			attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
			window.setAttributes(attrs);
			window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

		} else {
			attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
			window.setAttributes(attrs);
			window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

		}
	}

	@Override
	public void onResume() {
		// Log.i("slide", "ActivityFragment-->onResume");
//		length = SharedPrefsUtil.getValue(context, "progresslength", 3);
		Log.i("slide", "ActivityFragment-->onResume");
		if (playLayout.getAudio()) {
			btnSound.setBackgroundResource(R.drawable.playview_cloud_sound_h);
		} else
			btnSound.setBackgroundResource(R.drawable.playview_cloud_sound);

		super.onResume();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.menu_btn:
            context.finish();
			break;
		/*case R.id.playview_cloud_talk:

			break;*/
//		case R.id.playview_cloud_control:
//
//			if (isShowControlBtn) {
//				showControlBtnEx(false);
//			} else {
//				showControlBtnEx(true);
//			}
//			break;
//		case R.id.playview_cloud_focus:
//			break;
//		case R.id.playview_add:
//			break;
		case R.id.playview_rotate:
            if (this.isRotating) {
                btnRotate.setBackgroundResource(R.drawable.playview_rotate);
                playLayout.setRotation(0);
            } else {
                btnRotate.setBackgroundResource(R.drawable.playview_rotate_dark);
                playLayout.setRotation(180);
            }
            this.isRotating = !this.isRotating;
			break;
		case R.id.playview_cloud_sound:
			if (!playLayout.getAudio()) {
				playLayout.setIsAudio(true);
				btnSound.setBackgroundResource(R.drawable.playview_cloud_sound_h);
			} else {
				playLayout.setIsAudio(false);
				btnSound.setBackgroundResource(R.drawable.playview_cloud_sound);

			}
			break;
		case R.id.playview_cloud_stop:
			if (playerState != 1) {
				try {
					if (isPlaying) {
						Stop();
					} else {
						playLayout.play();
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			break;
		case R.id.btn_snap:
			try {
				playLayout.snap();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			break;
		case R.id.playview_cloud_stream:
			currentStream = (currentStream == 1 ? 0 : 1);
			initePlayDataAndPlay();
			break;
		case R.id.playview_cloud_alarm:
			if (alarmInfo == null) {
				break;
			}
			/*playLayout.setAlarm(appMain.getPlayerclient(),
					!Utils.showIfNotify(con, alarmInfo), new Handler() {

						@Override
						public void handleMessage(Message msg) {

							if (msg.what == AcAlertSettings.NOTIFY_SAVE_OK) {
								// Show.toast(con, R.string.commited);
								if (alarmInfo.iNotifyNum > 0) {
									alarmInfo.iNotifyNum = 0;
									btnAlarm.setImageResource(R.drawable.playview_cloud_alarm);
								} else {
									alarmInfo.iNotifyNum = 5;
									btnAlarm.setImageResource(R.drawable.playview_cloud_alarm_h);
								}

							}

						}
					});*/
			break;
		case R.id.btn_record:
			try {
				if (!playLayout.record()) {
					btnRecord.setChecked(false);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

	}

	/*@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub

		switch (checkedId) {
		case R.id.rb_prew1:
			playLayout.playCanvas(PlayLayout.ROW_TOTAL_1);
			setSharedSharedPreferences(PlayLayout.ROW_TOTAL_1);
			break;
		case R.id.rb_prew16:
			playLayout.playCanvas(PlayLayout.ROW_TOTAL_16);
			setSharedSharedPreferences(PlayLayout.ROW_TOTAL_16);
			break;
		case R.id.rb_prew4:
			playLayout.playCanvas(PlayLayout.ROW_TOTAL_4);
			setSharedSharedPreferences(PlayLayout.ROW_TOTAL_4);
			break;
		default:
			break;
		}

	}*/

	public void setSharedSharedPreferences(int rowTotal) {
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(ROW_TOTAL, rowTotal);
		editor.commit();
	}

	class ShowStopLayout implements ShowStopLayoutListener {
		boolean isMoveed = false;
		boolean isShown = false;

		@Override
		public void showStateListener(boolean isShow) {
		}

		@Override
		public void isMoveVisibleListener(boolean isMove) {
		}

		@Override
		public void isStop(boolean isStop) {
		}

	}

	class StateChange implements StateChangeListener {

		@Override
		public void stateChange(int index, int state, String f) {
			// TODO Auto-generated method stub
			// Log.i("playstate", "playstate:------>" + state);
			playerState = state;

			tvState.setText(showState(state));
			tvState1.setText(f + "");
		}

		@Override
		public void isPlaying(final int index, boolean isPlaying) {
			// TODO Auto-generated method stub
			// Log.i("playstate", "playstate:------>" + isPlaying);

			// playLayout.setScreenScale(!isPlaying);
			FgPlay.this.isPlaying = isPlaying;
			if (isPlaying) { // 播放截图

				btnStop.setBackgroundResource(R.drawable.playview_play);

				if (!isShot) {
					isShot = true;
					TDevNodeInfor tDevNodeInfor = playLayout.canvas[index].player
							.CameraQueryChInfo();// 查询设备码流信息
					if (tDevNodeInfor != null) {
						currentChannel = tDevNodeInfor.iChNo;
						currentStream = tDevNodeInfor.streamtype;
					}
					if (currentStream == 1) {
						btnStream.setImageResource(R.drawable.playview_sd);
					} else
						btnStream.setImageResource(R.drawable.playview_hd);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {

							// TODO Auto-generated method stub
							int rate[] = playLayout.getPlayRate();
							if (rate == null) {
								isShot = false;
								return;
							}
							if (rate[0] != 0 || rate[1] != 0) {
								try {
									playLayout.snap("/sdcard/NewUMEye/thumb/");
									new Handler().postDelayed(new Runnable() {
										@Override
										public void run() {
											boolean issnaping = playLayout.canvas[index].player
													.GetIsSnapPicture();
											Log.e("This issnaping thumb",
													"This issnaping thumb is "
															+ issnaping);
											if (issnaping == true)// 还在截图就不刷新
																	// 等下次再截图
											{
												isShot = false;
											} else
												new GetThumb().execute();
										}
									}, 500);

								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							} else
								isShot = false;
						}
					}, 500);

				}

			} else
                btnStop.setBackgroundResource(R.drawable.playview_puase);
		}

		@Override
		public void isRecord(int index, boolean isRecord) {
			// TODO Auto-generated method stub
			// Log.i("playstate", "playstate:------>" + isPlaying);
			btnRecord.setChecked(isRecord);
		}

		@Override
		public void isAudio(int index, boolean isAudio) {
			// TODO Auto-generated method stub

		}

		@Override
		public void isTalk(int index, boolean isTalk) {
			// TODO Auto-generated method stub
			// if (isTalk) {
			// btnTalk.setImageResource(R.drawable.playview_cloud_talk_h);
			// } else {
			// btnTalk.setImageResource(R.drawable.playview_cloud_talk);
			// }
			Log.w(TAG + "isTalk", "isTalk :---->" + isTalk);

		}

		@Override
		public void showControlBtn(int index, boolean isShow) {
			// TODO Auto-generated method stub

			if (isShow) {
				if (isShowControlBtn) {
					showControlBtnEx(false);
				} else
					showControlBtnEx(true);
			} else
				showControlBtnEx(false);

		}

		String showState(int state) {
			String ret;
			if (state == 1) {// 连接中
				ret = "连接中...";
			} else if (state == 2) {// 播放中
				ret = "播放中...";
			} else if (state == 3) {// 连接失败
				ret = "连接失败";
			} else if (state == 4) {// 停止中
				ret = "停止";
			} else if (state == -102) {// 密码错误
				ret = "密码错误";
			} else if (state == -101) {// 用户ID或用户名错误
				ret = "用户名错误";
			} else if (state == -111) {
				ret = "权限不够";
			} else if (state==0){// 准备就绪
				ret = "准备就绪";
			}else {// 
				ret = "未连接";
			}
			return ret;
		}

	}

	public void Stop() {

		playLayout.stop();
		if (isVisible()) {
			btnSound.setBackgroundResource(R.drawable.playview_cloud_sound);
			tvTitle.setText(titleName);
			if (down != null) {
				showControlBtnEx(false);
			}
		}

	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		// if (playLayout != null) {
		// playLayout.stopRun();
		// }

		super.onStop();
		Log.i("slide", "ActivityFragment-->onStop");
	}

	public long getDataCount() {
		if (playLayout == null) {
			return 0;
		}
		return playLayout.getDataCount();
	}
	public void stopAll() {
		playLayout.stopAll();
	}
	@Override
	public void onDestroy() {
		// if (playLayout != null) {
		// playLayout.stopRun();
		// }
        playLayout.release();
        playLayout.stop();
        playLayout.stopAll();
        playLayout.stopChannel();
        playLayout.stopDelayed(true);
        playLayout.stopRun();
        playLayout.stopThread();

		super.onDestroy();
		Log.i("slide", "ActivityFragment-->onDestroy,量量统计：");
//		long count = getDataCount();
//		appMain.setDataCount(count);
	}

}
